package com.xscha.tableforge.repository;

import com.xscha.soyue.common.core.utils.DateUtils;
import com.xscha.tableforge.model.entity.App;
import com.xscha.tableforge.model.vo.PageReq;
import com.xscha.tableforge.model.vo.PageResult;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.OrderField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.xscha.tableforge.jooq.tables.AppTable.APP;

@Repository
public class AppRepository {

    private final DSLContext dslContext;

    @Autowired
    public AppRepository(DSLContext dslContext) {
        this.dslContext = dslContext;
    }

    /**
     * 根据空间ID查找所有应用
     * @param spaceId 空间ID
     * @return 应用列表
     */
    public List<App> findAllBySpaceId(String spaceId) {
        return dslContext.select()
                .from(APP)
                .where(APP.SPACE_ID.eq(spaceId)
                        .and(APP.DELETED_TIME.isNull()))
                .orderBy(APP.CREATED_TIME.asc())
                .fetchInto(App.class);
    }

    /**
     * 根据ID查找应用
     * @param id 应用ID
     * @return 应用信息
     */
    public Optional<App> findById(String id) {
        return dslContext.select()
                .from(APP)
                .where(APP.ID.eq(id)
                        .and(APP.DELETED_TIME.isNull()))
                .fetchOptionalInto(App.class);
    }

    /**
     * 保存应用
     * @param appEntity 应用实体
     * @return 保存后的应用
     */
    public App save(App appEntity) {
        dslContext.insertInto(APP)
                .set(APP.ID, appEntity.getId())
                .set(APP.SPACE_ID, appEntity.getSpaceId())
                .set(APP.NAME, appEntity.getName())
                .set(APP.DISPLAY_ORDER, appEntity.getDisplayOrder())
                .set(APP.ICON, appEntity.getIcon())
                .set(APP.SCHEMA_PASS, appEntity.getSchemaPass())
                .set(APP.CREATED_TIME, appEntity.getCreatedTime())
                .set(APP.CREATED_BY, appEntity.getCreatedBy())
                .execute();
        return appEntity;
    }

    /**
     * 更新应用
     * @param appEntity 应用实体
     * @return 更新后的应用
     */
    public App update(App appEntity) {
        dslContext.update(APP)
                .set(APP.NAME, appEntity.getName())
                .set(APP.DISPLAY_ORDER, appEntity.getDisplayOrder())
                .set(APP.ICON, appEntity.getIcon())
                .set(APP.SCHEMA_PASS, appEntity.getSchemaPass())
                .set(APP.LAST_MODIFIED_BY, appEntity.getLastModifiedBy())
                .set(APP.LAST_MODIFIED_TIME, appEntity.getLastModifiedTime())
                .where(APP.ID.eq(appEntity.getId()))
                .execute();
        return appEntity;
    }

    /**
     * 软删除应用
     * @param id 应用ID
     * @param userId 操作用户ID
     */
    public void softDelete(String id, String userId) {
        dslContext.update(APP)
                .set(APP.DELETED_TIME, DateUtils.nowTimeStamp().toLocalDateTime())
                .set(APP.LAST_MODIFIED_BY, userId)
                .set(APP.LAST_MODIFIED_TIME, DateUtils.nowTimeStamp().toLocalDateTime())
                .where(APP.ID.eq(id))
                .execute();
    }

    /**
     * 分页查询空间下的应用
     * @param spaceId 空间ID
     * @param pageRequest 分页请求
     * @return 分页结果
     */
    public PageResult<App> findPageBySpaceId(String spaceId, PageReq pageRequest) {
        // 计算总记录数
        int total = dslContext.selectCount()
                .from(APP)
                .where(APP.SPACE_ID.eq(spaceId)
                        .and(APP.DELETED_TIME.isNull()))
                .fetchOneInto(Integer.class);
        
        // 构建排序条件
        List<OrderField<?>> orderFields = new ArrayList<>();
        if (pageRequest.getOrderBy() != null && !pageRequest.getOrderBy().isEmpty()) {
            Field<?> orderField = APP.field(pageRequest.getOrderBy());
            if ("desc".equalsIgnoreCase(pageRequest.getOrderDirection())) {
                orderFields.add(orderField.desc());
            } else {
                orderFields.add(orderField.asc());
            }
        } else {
            // 默认按order字段排序
            orderFields.add(APP.DISPLAY_ORDER.asc());
        }
        
        // 查询分页数据
        List<App> records = dslContext.select()
                .from(APP)
                .where(APP.SPACE_ID.eq(spaceId)
                        .and(APP.DELETED_TIME.isNull()))
                .orderBy(orderFields)
                .limit(pageRequest.getPageSize())
                .offset((pageRequest.getPageNum() - 1) * pageRequest.getPageSize())
                .fetchInto(App.class);
        
        return PageResult.of(records, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }
}